﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Mail;
using MammothMicro.SMTPGuard;
using MammothMicro.SMTPGuard.Common;
using MammothMicro.SMTPGuard.Filter;
using MammothMicro.SmtpGuardFilter.Common;

namespace MammothMicro.SmtpGuardFilter.Filter
{
    /// <summary>
    /// Checks against blocked email list
    /// </summary>
    public class BlockedEmailFilter :IEmailFilter
    {
        private List<string> _list = new List<string>();

        public bool Accept(MailMessage message)
        {
            if(_list.Exists(p => p == message.From.Address.ToLower()))
            {
                var msg = new SerializableMailMessage()
                              {Email = message, Id = new Guid(), FilteredBy = Tools.Filters.BlockedMailFilter};
                
                FilterManager.MailStore.Save(msg);
                return false;
            }
            return true;
        }

        public void Reload()
        {
            var path = System.IO.Path.GetDirectoryName(
                System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
            path = path.Remove(0, 6)+ @"\configuration\blockedemails.txt";
            var reader = new StreamReader(path);
            var text = reader.ReadToEnd().ToLower();
            reader.Close();
            const string delimiter = "\r\n";
            var t = text.Split(delimiter.ToCharArray());
            
            _list = t.ToList();
        }
    }
}


